<!-- 单位编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="700"
    :model-value="modelValue"
    :title="isUpdate ? '编辑商品' : '新增商品'"
    @update:model-value="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-row :gutter="16">
        <el-col :sm="12" :xs="24">
          <el-form-item label="商品图片" prop="logo">
            <ImageUpload
              v-model="form.logo"
              :item-style="imageUploadItemStyle"
              :button-style="imageUploadItemStyle"
              :limit="1"
              :previewProps="{ 'hide-on-click-modal': true }"
            />
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="form.name" clearable placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品价格" prop="cost_price">
            <el-input
              v-model="form.cost_price"
              clearable
              placeholder="请输入商品价格"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
            />
          </el-form-item>
          <el-form-item label="商品状态" prop="status">
            <el-radio-group v-model="form.status" placeholder="请选择状态">
              <el-radio label="正常" :value="1" />
              <el-radio label="禁用" :value="2" />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="商品编码" prop="code">
            <el-input :value="form.code || '自动生成'" clearable disabled placeholder="请输入商品编码" />
          </el-form-item>
          <el-form-item label="商品条形码" prop="bar_code">
            <el-input v-model="form.bar_code" clearable placeholder="请输入商品条形码" />
          </el-form-item>
          <el-form-item label="货主" prop="supplier_id">
            <el-select v-model="form.supplier_id" placeholder="请选择货主" clearable>
              <el-option v-for="item in supplierList" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="主单位" prop="unit">
            <el-select v-model="form.unit" placeholder="请选择主单位" clearable>
              <el-option v-for="item in unitList" :key="item.id" :value="item.name" :label="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="多单位状态" prop="multi_unit_status">
            <el-radio-group v-model="form.multi_unit_status" placeholder="请选择状态">
              <el-radio label="正常" :value="1" />
              <el-radio label="禁用" :value="2" />
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :sm="24">
          <el-form-item label="辅助单位" prop="multi_unit_status">
            <div class="flex w-full">
              <el-table
                :data="form.multi_unit"
                border
                empty-text="暂无辅助单位"
                stripe
                size="small"
                style="width: 100%"
                :max-height="300"
              >
                <el-table-column prop="unit" label="单位" align="center" :min-width="100">
                  <template #default="{ row, $index }">
                    <el-form-item label="" :prop="`multi_unit[${$index}].unit`" required>
                      <el-select v-model="row.unit" placeholder="请选择单位" size="small" clearable>
                        <el-option
                          v-for="item in unitList"
                          :key="item.id"
                          :disabled="item.name !== row.unit && [form.unit, ...form.multi_unit.map(v => v.unit)].includes(item.name)"
                          :value="item.name"
                          :label="item.name"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="ratio" label="转换比例" align="center" :min-width="100">
                  <template #default="{ row, $index }">
                    <el-form-item label="" :prop="`multi_unit[${$index}].ratio`" required>
                      <el-input
                        v-model="row.ratio"
                        size="small"
                        :input-style="{ textAlign: 'center' }"
                        clearable
                        placeholder="请输入转换比例"
                        oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="操作" align="center" width="100">
                  <template #default="{ $index }">
                    <el-link type="danger" underline="never" @click="removeUnit($index)">
                      <span
                        class="text-12px"
                      >删除</span>
                    </el-link>
                  </template>
                </el-table-column>
              </el-table>
              <el-button class="ml-12px" type="primary" icon="IconElPlus" plain size="small" @click="addUnit">新增</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="updateModelValue(false)">
        取消
      </el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
import { listUnit } from '@/api/common'
import { updateProduct } from '@/api/mch-archives/product'
import ImageUpload from '@/components/ImageUpload/index.vue'

const props = defineProps({
  /** 弹窗是否打开 */
  modelValue: Boolean,
  /** 修改回显的数据 */
  data: Object,
  supplierList: Array,
})

const emit = defineEmits(['done', 'update:modelValue'])

const imageUploadItemStyle = { width: '80px', height: '80px', margin: 0 }

/** 是否是修改 */
const isUpdate = ref(false)

/** 提交状态 */
const loading = ref(false)

/** 表单实例 */
const formRef = ref(null)

const [unitList] = utils.useGetList(listUnit)

/** 表单数据 */
const [form, resetFields, assignFields] = utils.useFormData({
  id: undefined,
  name: '',
  logo: '',
  code: '',
  bar_code: '',
  cost_price: '',
  unit: '',
  multi_unit: [],
  supplier_id: '',
  multi_unit_status: 1, // 1 启用 2 禁用
  status: 1, // 1 启用 2 禁用
})

/** 表单验证规则 */
const rules = reactive({
  name: [
    {
      required: true,
      message: '请输入商品名称',
      type: 'string',
      trigger: 'blur',
    },
  ],
  // code: [
  //   {
  //     required: true,
  //     message: '请输入商品编码',
  //     type: 'string',
  //     trigger: 'blur',
  //   },
  // ],
  bar_code: [
    {
      required: false,
      message: '请输入商品条形码',
      type: 'string',
      trigger: 'blur',
    },
  ],
  cost_price: [
    {
      required: true,
      message: '请输入商品价格',
      trigger: 'blur',
    },
    {
      pattern: /^(?!(0\d*$))\d+(?:\.+\d*)?$/,
      message: '请输入正确的金额格式',
      trigger: 'blur',
    },
  ],
  unit: [
    {
      required: true,
      message: '请选择商品单位',
      trigger: 'change',
    },
  ],
  supplier_id: [
    {
      required: true,
      message: '请选择货主',
      trigger: 'change',
    },
  ],
})

function addUnit() {
  form.multi_unit.push({
    unit: '',
    ratio: '',
  })
}

function removeUnit(index) {
  form.multi_unit.splice(index, 1)
}

/** 保存编辑 */
function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true

    updateProduct(form)
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          updateModelValue(false)
          emit('done')
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

/** 更新modelValue */
function updateModelValue(value) {
  emit('update:modelValue', value)
}

watch(
  () => props.modelValue,
  (modelValue) => {
    if (modelValue) {
      if (props.data) {
        assignFields(props.data)
        isUpdate.value = true
      }
      else {
        isUpdate.value = false
      }
    }
    else {
      resetFields()
      formRef.value?.clearValidate?.()
    }
  },
)
</script>
